<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Store;

use App\Api\Controllers\BaseController;
use App\Exceptions\BizException;
use App\Models\OperationLog;
use App\Models\Store;
use App\Models\User;
use App\Services\PassVerifyService;
use App\Traits\ResponseTrait;
use App\Util\ListUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use function EasyWeChat\Kernel\Support\get_client_ip;

class SignController extends BaseController
{

    use ResponseTrait;

    public function signSet(Request $request): string
    {
        DB::beginTransaction();
        try {
            $user = $this->parseToken();
            $store_id = $request->post("store_id");
            $is_sign = $request->post("is_sign");
            $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
            $systemUserArray = ListUtil::createListsNode($systemUserArray);
            $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
            $userCollection = ListUtil::listsNodeToArray([$userCollection]);
            $userCollectionIds = array_column($userCollection, "id");
            $store = Store::query()->whereIn("user_id", $userCollectionIds)->where("store_id", $store_id)->first();
            if (empty($store)) {
                return $this->errorResponse("店铺不存在");
            }
            $pash = $request->path();
            $pass = $request->get('pass', '');
            $pass = substr(base64_decode($pass), 0, -5);

            $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            $pass_verify = json_decode($pass_verify, true);
            if ($pass_verify['status'] == '1') {
                $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
            } else {
                throw new \Exception("验证不通过");
            }
            $origin_is_sign = $store->is_sign;
            $store->is_sign = $is_sign;
            if (!$store->save()) {
                throw new BizException("更新失败");
            }
            //操作记录
            OperationLog::query()->insert([
                "agent_id" => $user->user_id,
                "pass_id" => $pass_id,
                "ip" => get_client_ip(),
                "remark" => "修改签约状态 ,修改前:" . $origin_is_sign . ",修改后:" . $is_sign,
                "type" => 18,
                "create_time" => date("Y-m-d H:i:s", time())
            ]);
            DB::commit();
            return $this->successResponse("ok", [
                "store_id" => $store_id,
                "is_sign" => $is_sign
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorResponse($e->getMessage());
        }
    }


}